# -*- coding: utf-8 -*-
import hashlib

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2095': {
        'API_KEY': 'f0ca888b9a4644b4abe1473a538cc179',
        'gateway': 'http://pay.hhrwlb.top/chargebank.aspx',
        'query_gateway': 'http://pay.hhrwlb.top/search.aspx?orderid={}&parter={}&sign={}',
    },
    '1981': {  # dwc qq1.5%，（1---1000）。支付宝，微信费率都是2.6%，（5---3000）。d0结算。
        'API_KEY': 'e9e8d048a10c483dae16e396fd03e369',
        'gateway': 'http://pay.jxtx6699.com/chargebank.aspx',
        'query_gateway': 'http://pay.jxtx6699.com/search.aspx?orderid={}&parter={}&sign={}',
    },
    '2380': {  # witch，御亿支付 支付宝3%（10---3000），微信3%（50---3000），qq2%（10---1000）。d0结算。
        'API_KEY': '19e2d90c0c5c40b1b4876decbbd23f3e',
        'gateway': 'http://pay.xinyiyupay.com/chargebank.aspx',
        'query_gateway': 'http://pay.xinyiyupay.com/search.aspx?orderid={}&parter={}&sign={}',
    },
    '100003': {  # witch，诺驰 支付宝2.5%（1---1W），QQ1.5%（1---5千）D0结算
        'API_KEY': '5299b9bf412c48b8bc70580a3ee06524',
        'gateway': 'http://ncpay.nuochia.cn/chargebank.aspx',
        'query_gateway': 'http://ncpay.nuochia.cn/search.aspx?orderid={}&parter={}&sign={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def gen_order_str(parameter):
    return 'parter={}&type={}&value={}&orderid={}&callbackurl={}'.format(
        parameter['parter'], parameter['type'], parameter['value'],
        parameter['orderid'], parameter['callbackurl'])


def generate_order_sign(parameter, key):
    s = gen_order_str(parameter) + key
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest()
    _LOGGER.info(u'ruiyunpay origin string: %s, sign:%s', s, sign)
    return sign


def generate_query_sign(parameter, key):
    s = 'orderid={}&parter={}{}'.format(parameter['orderid'], parameter['parter'], key)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest()
    _LOGGER.info(u'ruiyunpay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    s = 'orderid={}&opstate={}&ovalue={}{}'.format(params['orderid'], params['opstate'], params['ovalue'], key)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("ruiyunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 992	支付宝扫码
# 1004	微信扫码
# 1005	微信wap版
# 1006	支付宝wap版
# 1593	QQ钱包扫码
# 1594	QQwap
# 2087	网银快捷PC
# 2088	网银快捷wap
# 1007	银联码
# 1008	京东钱包扫码
# 1009	京东钱包wap

# 诺驰支付
# BankWAP	网银WAP
# ALIPAY_WAP	支付宝WAP
# WEIXIN_WAP	微信WAP
# QQ_WAP	QQWAP
# QQ_QR	QQ钱包
# JD_QR	京东支付
# UNION_QR	银联扫码
# FastPay	网银快捷
# JD_WAP	京东WAP
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '1005'
    elif service == 'alipay':
        payType = '1006'
    elif service == 'qq':
        payType = '1593'
    elif service == 'qq1':
        payType = '1594'
    elif service == 'jd':
        payType = '1009'
    elif service == 'nc_alipay':
        payType = 'ALIPAY_WAP'
    elif service == 'nc_wxpay':
        payType = 'WEIXIN_WAP'
    elif service == 'nc_qq':
        payType = 'QQ_WAP'
    elif service == 'nc_jd':
        payType = 'JD_WAP'
    elif service == 'nc_quick':
        payType = 'FastPay'
    else:
        payType = '2088'
    return payType


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')
    p_dict = {
        'parter': app_id,
        'type': _get_pay_type(service),
        'value': pay_amount,
        'orderid': str(pay.id),
        'callbackurl': '{}/pay/api/{}/ruiyunpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)
    }
    sign = generate_order_sign(p_dict, key)
    url = _get_gateway(app_id) + '?' + gen_order_str(p_dict) + '&sign=' + sign
    _LOGGER.info("ruiyunpay data url: %s", url)
    return {'charge_info': url, }


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("ruiyunpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('ruiyunpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['opstate'])
    trade_no = data.get('sysorderid')
    total_fee = float(data['ovalue'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 0:
        _LOGGER.info('ruiyunpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'parter': app_id,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    response = requests.get(_get_query_gateway(app_id).format(p_dict['orderid'], p_dict['parter'], p_dict['sign']))
    _LOGGER.info(u'ruiyunpay create query: %s', response.text)
    if response.status_code == 200:
        trade_status = int(_get_str(response.text, 'opstate=', '&'))
        total_fee = float(_get_str(response.text, 'ovalue=', '&'))
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 0:
            _LOGGER.info('ruiyunpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('ruiyunpay data error, status_code: %s', response.status_code)
